/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：main.c
*   创 建 者：baichao
*   创建日期：2024年04月16日
*   描    述：
*
================================================================*/

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode *swapPairs(struct ListNode *head) {
  if (head == NULL || head->next == NULL) return head;

  struct ListNode *prePairTail = head, *firstNode = head,
                  *secondNode = head->next;
  head = head->next;
  bool isFirstPair = true;

  while (firstNode != NULL && secondNode != NULL) {
    firstNode->next = secondNode->next;
    secondNode->next = firstNode;
    if (isFirstPair == false) {
      prePairTail->next = secondNode;
    }
    prePairTail = firstNode;
    isFirstPair = false;

    if (prePairTail != NULL) {
      firstNode = prePairTail->next;
    } else {
      break;
    }
    if (prePairTail->next != NULL) {
      secondNode = prePairTail->next->next;
    } else {
      break;
    }
  }
  return head;
}

int main() {
  struct ListNode *currNode = NULL;
  struct ListNode *listA = (struct ListNode *)malloc(sizeof(struct ListNode));

  listA->val = 1;
  listA->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = listA->next;

  currNode->val = 2;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 3;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 4;
  currNode->next = NULL;

  swapPairs(listA);
}
